package cn.com.kisen.kdc.config.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(
        basePackages = "cn.com.kisen.kdc.mapper.weighing.smartlms",
        sqlSessionFactoryRef = "lmsSSF",
        sqlSessionTemplateRef = "lmsSST")
public class LmsConfig {

    @Bean(name = "lmsDS")
    @Qualifier("lmsDS")
    @ConfigurationProperties(prefix = "spring.datasource.lms")
    public DataSource lmsDS() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "lmsSSF")
    @Primary
    public SqlSessionFactory lmsSSF(
            @Qualifier("lmsDS") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mybatis/mapper/weighing/smartlms/*.xml"));
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    @Bean(name = "lmsSST")
    @Primary
    public SqlSessionTemplate lmsSST(
            @Qualifier("lmsSSF") SqlSessionFactory sqlSessionFactory)
            throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(name = "lmsDSTM")
    @Primary
    public DataSourceTransactionManager lmsDSTM(@Qualifier("lmsDS") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}